package com.dhu.stylefit.service;

import com.dhu.stylefit.dao.ClothesOne;
import com.dhu.stylefit.dao.ClothesOneRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.regex.Pattern;

@Service
public class StyleAnalyzeService {
    
    @Autowired
    private ClothesOneRepository clothesRepository;
    
    @Value("${openai.api.key}")
    private String openaiApiKey;
    
    @Value("${openai.api.base-url}")
    private String openaiBaseUrl;
    
    private final RestTemplate restTemplate = new RestTemplate();
    
    public Map<String, Object> analyzeStyle(String userRequest) {
        try {
            // 获取所有衣服数据
            List<ClothesOne> allClothes = clothesRepository.findAll();
            
            // 准备衣服信息
            StringBuilder clothesInfo = new StringBuilder();
            for (ClothesOne clothes : allClothes) {
                clothesInfo.append(String.format("ID: %d, 描述: %s\n", clothes.getId(), clothes.getDescription()));
            }
            
            // 准备OpenAI API请求
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + openaiApiKey);
            
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "gemini-1.5-flash");
            
            List<Map<String, String>> messages = new ArrayList<>();
            Map<String, String> systemMessage = new HashMap<>();
            systemMessage.put("role", "system");
            systemMessage.put("content", String.format("你是一个专业的时尚顾问。用户请求如下：%s。如果用户希望你推荐衣服，请根据以下衣服信息返回符合要求的所有衣服ID，用逗号分隔：\n%s。如果用户不需要推荐衣服，请直接回答用户的问题。", 
                userRequest, clothesInfo.toString()));
            
            Map<String, String> userMessage = new HashMap<>();
            userMessage.put("role", "user");
            userMessage.put("content", "请根据我的请求判断是否需要返回衣服ID。如果是，请返回符合要求的所有衣服ID，用逗号分隔。如果不是，请对我请求的问题进行分析返回答案。");
            
            messages.add(systemMessage);
            messages.add(userMessage);
            requestBody.put("messages", messages);
            
            HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);
            
            // 调用OpenAI API
            Map<String, Object> response = restTemplate.postForObject(
                openaiBaseUrl + "/chat/completions",
                request,
                Map.class
            );
            
            // 解析响应
            if (response != null && response.containsKey("choices")) {
                List<Map<String, Object>> choices = (List<Map<String, Object>>) response.get("choices");
                if (!choices.isEmpty()) {
                    Map<String, Object> choice = choices.get(0);
                    Map<String, String> message = (Map<String, String>) choice.get("message");
                    String content = message.get("content");
                    
                    // 检查是否是ID列表
                    if (Pattern.matches("^\\d+(,\\s*\\d+)*$", content)) {
                        List<String> clothesIds = Arrays.asList(content.split(","));
                        Map<String, Object> result = new HashMap<>();
                        result.put("type", "clothes_ids");
                        result.put("data", clothesIds);
                        return result;
                    } else {
                        Map<String, Object> result = new HashMap<>();
                        result.put("type", "answer");
                        result.put("data", content);
                        return result;
                    }
                }
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("type", "answer");
            result.put("data", "没有找到符合条件的衣服或答案。");
            return result;
            
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("type", "error");
            result.put("data", "API调用出错：" + e.getMessage());
            return result;
        }
    }
} 